package com.code.leetcode._202504;
/**查询旋转排序数组**/
public class SearchRotateArray {

    //先找旋转后二分
    public int search(int[] nums, int target) {
        int n = nums.length, idx = -1;
        for (int i = 0; i < n - 1 && idx == -1; i++) {
            if (nums[i] > nums[i + 1]) idx = i;
        }
        int ans = find(nums, 0, idx, target);
        if (ans != -1) return ans;
        return idx + 1 < n ? find(nums, idx + 1, n - 1, target) : ans;
    }
    int find(int[] nums, int l, int r, int target) {
        while (l < r) {
            int mid = l + r >> 1;
            if (nums[mid] >= target) r = mid;
            else l = mid + 1;
        }
        return nums[l] == target ? l : -1;
    }

    //再次二分
    public int search1(int[] nums, int target) {
        int n = nums.length;

        // 第一次「二分」：从中间开始找，找到满足 >=nums[0] 的分割点（旋转点）
        int l = 0, r = n - 1;
        while (l < r) {
            int mid = l + r + 1 >> 1;
            if (nums[mid] >= nums[0]) l = mid;
            else r = mid - 1;
        }

        // 第二次「二分」：通过和 nums[0] 进行比较，得知 target 是在旋转点的左边还是右边
        if (target >= nums[0]) {
            l = 0;
        } else {
            l = l + 1; r = n - 1;
        }
        while (l < r) {
            int mid = l + r >> 1;
            if (nums[mid] >= target) r = mid;
            else l = mid + 1;
        }

        return nums[r] == target ? r : -1;
    }
}
